package com.ww.core.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import android.os.Environment;

/**
 * 文件工具类
 * @version 2012-10-17
 * @author wangw
 */
public class FileUtil {

	/**
	 * 通过一个InputStream获取内容
	 * @param inputStream
	 * @return
	 */
	public static void copyDbFile(InputStream is, String path, String fileName) {
		try {
			File dbDir = new File(path);
			if (!dbDir.exists()) {
				dbDir.mkdirs();
			}
			
			File dbFile = new File(path + fileName);	
			if (!dbFile.exists()) {
				Logger.info("path + fileName====================="+path + fileName);
				FileOutputStream os = new FileOutputStream(path + fileName);
				byte[] buffer = new byte[1024];
				int count = 0;
				// 灏嗛潤鎬佹暟鎹簱鏂囦欢鎷疯礉鍒扮洰鐨勫湴
				while ((count = is.read(buffer)) > 0) {
					os.write(buffer, 0, count);
				}
				is.close();
				os.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 通过一个InputStream获取内容
	 * @param inputStream
	 * @return
	 */
	public static String getString(InputStream inputStream) {
		InputStreamReader inputStreamReader = null;
		try {
			inputStreamReader = new InputStreamReader(inputStream, "gbk");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		BufferedReader reader = new BufferedReader(inputStreamReader);
		StringBuffer sb = new StringBuffer("");
		String line;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	/**
	 * 通过txt文件的路径获取其内容
	 * @param filepath
	 * @return
	 */
	public static String getString(String filepath) {
		File file = new File(filepath);
		FileInputStream fileInputStream = null;
		try {
			fileInputStream = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return getString(fileInputStream);
	}
	
	/**
	 * 在sdcard卡上创建文件
	 * @param fileName   文件名
	 * @param content   文件内容
	 */
	public static void saveFile(String fileName, String content) {
			File file = new File(Environment.getExternalStorageDirectory() + "/daydayup/txt/");
			if (!file.exists()) {
				file.mkdirs();
			}

			char[] c = new char[content.length()];
			for (int i = 0; i < content.length(); i++) {
				c[i] = content.charAt(i);
			}
			FileWriter fw = null;
			try {
				fw = new FileWriter(Environment.getExternalStorageDirectory() + "/daydayup/txt/" + fileName);
				fw.write(c);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (fw != null) {
						fw.close();
					}
				} catch (IOException e) {
				}
			}
	}
}
